<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek Chat Clone</title>
    <style>
        /* 深色系官方风格 */
        :root {
            --primary-color: #10a37f;
            --bg-color: #343541;
            --sidebar-bg: #202123;
            --message-bg-user: #444654;
            --message-bg-bot: #343541;
            --border-color: rgba(255,255,255,0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            display: flex;
            height: 100vh;
            background: var(--bg-color);
            color: #d1d5db;
            font-family: -apple-system, system-ui, sans-serif;
        }

        /* 左侧边栏 */
        .sidebar {
            width: 260px;
            background: var(--sidebar-bg);
            padding: 12px;
            display: flex;
            flex-direction: column;
        }

        .new-chat-btn {
            padding: 12px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            margin-bottom: 12px;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
        }

        /* 侧边栏优化 */
        .chat-item {
            position: relative;
            padding: 12px 16px; /* 调整内边距 */
            /* 原padding: 12px 40px 12px 16px; */
            border-radius: 0.375rem;
            margin: 4px 0;
            transition: all 0.2s;
            color: #ececf1;
            font-size: 0.875rem;
            cursor: pointer;
        }

        .chat-item.active {
            background: rgba(64,65,79,0.8);
        }

        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(0,0,0,0.1);
        }

        ::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 4px;
        }

        /* 主聊天区域 */
        .main-chat {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
            height: 100vh;
        }

        #chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            scroll-behavior: smooth;
        }

        /* 消息气泡优化 */
        .message {
            max-width: 48rem;
            margin: 1.25rem auto;
            padding: 1.5rem;
            border-radius: 0.375rem;
            line-height: 1.5;
            font-size: 1rem;
            position: relative;
            word-wrap: break-word;
            white-space: pre-wrap;
        }

        .user-message {
            background: var(--message-bg-user);
            margin-left: auto;
            border-top-right-radius: 0.25rem;
            border-bottom-right-radius: 0.25rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .bot-message {
            background: var(--message-bg-bot);
            margin-right: auto;
            border-top-left-radius: 0.25rem;
            border-bottom-left-radius: 0.25rem;
            color: #ececf1;
        }

        /* 输入区域优化 */
        #input-container {
            display: flex;
            gap: 8px;
            align-items: flex-end;
            padding: 12px;
            flex-shrink: 0;
        }

        #user-input {
            flex: 1;
            min-height: 44px;
            max-height: 200px;
            padding: 10px 16px;
            margin: 0 8px;
            background: rgba(64,65,79,0.8);
            border: 1px solid var(--border-color);
            border-radius: 0.375rem;
            color: #ececf1;
            font-size: 1rem;
            line-height: 1.5;
            resize: none;
            transition: all 0.2s;
        }

        #user-input:focus {
            outline: none;
            box-shadow: 0 0 0 2px rgba(16,163,127,0.5);
        }

        /* 发送按钮 */
        #send-btn {
            padding: 8px 16px;
            background: var(--primary-color);
            border: none;
            border-radius: 0.375rem;
            color: white;
            cursor: pointer;
            transition: all 0.2s;
        }

        #send-btn:hover {
            background: #0d8a6d;
            transform: translateY(-1px);
        }

        .send-actions {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        /* 加载动画 */
        .loading-dots {
            display: flex;
            align-items: center;
            min-height: 1.5em;
            white-space: nowrap;
        }

        .loading-dots::after {
            content: '···';
            display: inline-block;
            width: 4ch;
            font-family: monospace;
            animation: dots 1.4s steps(4, end) infinite;
            overflow: hidden;
            vertical-align: bottom;
        }

        @keyframes dots {
            0% { width: 1ch; }
            33% { width: 2ch; }
            66% { width: 3ch; }
            100% { width: 4ch; }
        }

        /* 历史记录样式 */
        .chat-time {
            font-size: 12px;
            color: #8e8e9e;
            margin-top: 4px;
        }

        .chat-title {
            max-width: 100%; /* 使用父容器全部宽度 */
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: block;  /* 确保块级元素特性 */
            padding-right: 20px; /* 为菜单按钮预留空间 */
        }

        /* 菜单样式 */
        .chat-menu {
            position: absolute;
            right: 16px; /* 配合padding调整 */
            /* 原right: 12px; */
            top: 50%;
            transform: translateY(-50%);
            z-index: 100; /* 增加层级 */
        }

        .menu-trigger {
            background: transparent;
            border: none;
            color: #8e8e9e;
            padding: 4px;
            cursor: pointer;
            font-size: 1.2rem;
        }

        .menu-content {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            margin-top: 8px;
            z-index: 200; /* 高于其他元素 */
            min-width: 100px;
            background: var(--sidebar-bg);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3); /* 更明显的阴影 */
        }

        /* 新增菜单悬停逻辑 */
        .chat-menu:hover .menu-content,
        .menu-content:hover {
            display: block;
        }

        .menu-content::before {
            content: '';
            position: absolute;
            bottom: 100%;
            right: 8px;
            border-width: 6px;
            border-style: solid;
            border-color: transparent transparent var(--sidebar-bg) transparent;
        }

        .menu-item {
            display: block;
            width: 100%;
            padding: 8px 16px;
            background: none;
            border: none;
            color: #ececf1;
            text-align: left;
            cursor: pointer;
        }

        .menu-item:hover {
            background: rgba(255,255,255,0.1);
        }

        .chat-item:hover .menu-content,
        .menu-content:hover {
            display: block;
        }

        /* 防止父项hover影响 */
        .chat-item:hover {
            background: rgba(255,255,255,0.05); /* 保持原有hover效果 */
            position: relative; /* 创建新的层叠上下文 */
        }

        /* 增加历史项间距 */
        .chat-item {
            margin: 8px 0; /* 增加垂直间距 */
            position: relative;
        }
    </style>
</head>
<body>
    <!-- 左侧边栏 -->
    <div class="sidebar">
        <button class="new-chat-btn" onclick="createNewChat()">+ 新对话</button>
        <div class="history-list" id="historyList"></div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-chat">
        <div id="chat-container"></div>
        <div id="input-container">
            <div class="input-actions">
                <button class="icon-btn" id="upload-btn" style="display: none">
                    <svg>...</svg>
                </button>
            </div>
            <textarea 
                id="user-input" 
                placeholder="输入消息..." 
                rows="1"
                oninput="autoResize(this)"
                onkeydown="handleKeydown(event)"
            ></textarea>
            <div class="send-actions">
                <button id="send-btn" onclick="sendMessage()">发送</button>
            </div>
        </div>
    </div>

    <script>
        // 对话管理逻辑
        let currentChatId = null;
        let chats = JSON.parse(localStorage.getItem('chats') || '[]');

        // 新增菜单管理逻辑
        let activeMenu = null;

        document.addEventListener('click', (e) => {
            // 关闭非当前菜单
            if (!e.target.closest('.chat-menu')) {
                if (activeMenu) {
                    activeMenu.querySelector('.menu-content').style.display = 'none';
                    activeMenu = null;
                }
            }
        });

        // 初始化加载历史
        function initHistory() {
            const historyList = document.getElementById('historyList');
            historyList.innerHTML = '';
            
            chats.forEach(chat => {
                const item = document.createElement('div');
                item.className = 'chat-item';
                item.dataset.chatId = chat.id;

                const rawText = chat.messages[0]?.content || '新对话';
                const truncatedText = rawText.substring(0, 30);

                const time = new Date(chat.timestamp).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
                
                item.innerHTML = `
                    <div class="chat-title">${chat.customName || truncatedText}</div>
                    <div class="chat-time">${time}</div>
                    <div class="chat-menu">
                        <button class="menu-trigger">&#8942;</button>
                        <div class="menu-content">
                            <button class="menu-item">重命名</button>
                            <button class="menu-item">删除</button>
                        </div>
                    </div>
                `;

                item.querySelector('.menu-item:nth-child(1)').onclick = (e) => {
                    e.stopPropagation();
                    renameChat(chat.id);
                };
                item.querySelector('.menu-item:nth-child(2)').onclick = (e) => {
                    e.stopPropagation();
                    deleteChat(chat.id);
                };
                item.onclick = (e) => {
                    if (!e.target.closest('.chat-menu')) {
                        loadChat(chat.id);
                    }
                };

                historyList.appendChild(item);

                const menuTrigger = item.querySelector('.menu-trigger');
                const menuContent = item.querySelector('.menu-content');
        
                menuTrigger.onclick = (e) => {
                    e.stopPropagation();
                    // 关闭其他菜单
                    if (activeMenu && activeMenu !== menuContent) {
                        activeMenu.style.display = 'none';
                    }
                    // 切换当前菜单
                    menuContent.style.display = 
                        menuContent.style.display === 'block' ? 'none' : 'block';
                    activeMenu = menuContent;
                };
            });

            if (chats.length === 0) createNewChat();
            else loadChat(chats[0].id);
        }

        // 创建新对话
        function createNewChat() {
            currentChatId = Date.now().toString();
            const newChat = {
                id: currentChatId,
                messages: [],
                timestamp: new Date().toISOString()
            };
            chats.unshift(newChat);
            saveChats();
            initHistory();
            clearChatContainer();
        }

        // 加载对话
        function loadChat(chatId) {
            document.querySelectorAll('.chat-item').forEach(item => {
                item.classList.remove('active');
            });
            
            const currentItem = [...document.querySelectorAll('.chat-item')]
                .find(item => item.dataset.chatId === chatId);
            if(currentItem) {
                currentItem.classList.add('active');
            }

            currentChatId = chatId;
            const chat = chats.find(c => c.id === chatId);
            clearChatContainer();
            chat.messages.forEach(msg => {
                appendMessage(msg.role === 'user' ? 'user' : 'bot', msg.content);
            });
        }

        // 保存到 localStorage
        function saveChats() {
            localStorage.setItem('chats', JSON.stringify(chats));
        }

        // 清空聊天区域
        function clearChatContainer() {
            document.getElementById('chat-container').innerHTML = '';
        }

        // 消息处理逻辑
        function appendMessage(role, content) {
            const container = document.getElementById('chat-container');
            const msgDiv = document.createElement('div');
            msgDiv.className = `message ${role}-message`;
            msgDiv.innerHTML = content;
            container.appendChild(msgDiv);
            container.scrollTop = container.scrollHeight;
        }

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('user-input');
            const message = input.value.trim();
            if (!message) return;

            input.value = '';
            appendMessage('user', message);

            const container = document.getElementById('chat-container');
            const loadingMsg = document.createElement('div');
            loadingMsg.className = 'message bot-message loading-dots';
            loadingMsg.textContent = '思考中';
            container.appendChild(loadingMsg);
            container.scrollTop = container.scrollHeight;

            try {
                const requestBody = {
                    question: message,
                    history: getCurrentChat().messages.map(msg => ({
                        role: msg.role || 'user',
                        content: (msg.content || '').toString()
                    }))
                };

                const response = await fetch('deepseek.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });

                const data = await response.json();
                loadingMsg.remove();

                if (data.error) {
                    appendMessage('bot', `错误: ${data.error}`);
                } else {
                    appendMessage('bot', data.answer);
                    saveMessageToHistory('user', message);
                    saveMessageToHistory('assistant', data.answer);
                }
            } catch (error) {
                loadingMsg.remove();
                appendMessage('bot', '请求失败，请检查网络');
                console.error('Error:', error);
            }
        }

        // 辅助函数
        function getCurrentChat() {
            return chats.find(c => c.id === currentChatId);
        }

        function saveMessageToHistory(role, content) {
            const chat = getCurrentChat();
            chat.messages.push({ role, content });
            saveChats();
        }

        // 输入处理
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = textarea.scrollHeight + 'px';
        }

        function handleKeydown(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        }

        // 删除对话
        function deleteChat(chatId) {
            chats = chats.filter(c => c.id !== chatId);
            saveChats();
            initHistory();
        }

        // 重命名对话
        function renameChat(chatId) {
            const chat = chats.find(c => c.id === chatId);
            const newName = prompt(
                '输入新名称',
                chat.customName || chat.messages[0]?.content.substring(0, 30) || '新对话'
            );
            
            if (newName) {
                chat.customName = newName;
                saveChats();
                const item = document.querySelector(`.chat-item[data-chat-id="${chatId}"]`);
                if (item) {
                    item.querySelector('.chat-title').textContent = newName;
                }
            }
        }

        // 初始化
        initHistory();

        // 事件监听
        document.getElementById('user-input').addEventListener('paste', function(e) {
            setTimeout(() => autoResize(this), 0);
        });

        document.addEventListener('click', (e) => {
            if (!e.target.closest('.chat-menu')) {
                document.querySelectorAll('.menu-content').forEach(menu => {
                    menu.style.display = 'none';
                });
            }
        });
    </script>
</body>
</html>